import React, { useState, useEffect } from "react";
import { View } from "@tarojs/components";

import "./index.less";

export default (props) => {
  const [open, setOpen] = useState(false); // 展开控制
  const [title, setTitle] = useState(""); // 点击btn的名字
  const [key, setKey] = useState("id"); // 数据key
  const [value, setValue] = useState("name"); // 数据value
  useEffect(() => {
    props.key && setKey(props.key);
    props.value && setValue(props.value);
  }, [props]);
  const selectItem = async (item) => {
    setTitle(item[value]);
    props.onchange && props.onchange(item);
    setOpen(false);
  };
  const openSelect = (e) => {
    e.stopPropagation();
    if (!open) {
      props.onclick &&
        props.onclick(() => {
          setOpen(!open);
        });
    } else {
      setOpen(!open);
    }
  };
  const closeSelect = () => {
    setOpen(false);
  };
  return (
    <View className={"selectDown " + props.className}>
      {open && <View className="downBg" onClick={closeSelect}></View>}
      <View className="downTitle" onClick={openSelect}>
        {props.title ? props.title : title}
        <View
          className={`iconfont ${open ? "icon-xiangshang" : "icon-xiangxia"}`}
        ></View>
      </View>
      {open && (
        <View className="downCont">
          {props.data?.length > 0 ? (
            props.data?.map((item) => {
              return (
                <View
                  className={`downItem ${
                    props.selectValue && props.selectValue == item[key]
                      ? "active"
                      : ""
                  }`}
                  onClick={() => {
                    selectItem(item);
                  }}
                >
                  {item[value]}
                </View>
              );
            })
          ) : (
            <View className="downItem">暂无列表</View>
          )}
        </View>
      )}
    </View>
  );
};
